package spring.springbucks.filter;

import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.proxy.jdbc.ConnectionProxy;
import com.alibaba.druid.proxy.jdbc.StatementProxy;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;

@Slf4j
public class ConnectionLogFilter extends FilterEventAdapter {

  @Override
  public void connection_connectBefore(FilterChain chain, Properties info) {
    log.info("BEFORE CONNECTION!");

  }

  @Override
  public void connection_connectAfter(ConnectionProxy connection) {
    log.info("AFTER CONNECTION!");
  }

  @Override
  protected void statementExecuteUpdateBefore(StatementProxy statement, String sql) {
    sqlValidate(statement);
  }

  @Override
  protected void statementExecuteBefore(StatementProxy statement, String sql) {
    sqlValidate(statement);
  }

  @Override
  protected void statementExecuteBatchBefore(StatementProxy statement) {
    sqlValidate(statement);
  }

  @Override
  protected void statementExecuteQueryBefore(StatementProxy statement, String sql) {
    sqlValidate(statement);
  }

  private boolean sqlValidate(StatementProxy statement) {

    //SQLStatementParser parser = new MySqlStatementParser(statement.getSqlStat().getSql());
    //SQLStatement sqlStatement = parser.parseStatement();
    //MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
    //sqlStatement.accept(visitor);
    //// * 不允许进行 SQL 拼接。
    //List<TableStat.Condition> concatSql =
    //  visitor.getConditions().stream().filter(condition -> condition.getValues() != null && condition.getValues().size() > 0)
    //    .collect(Collectors.toList());
    //if (concatSql != null && concatSql.size() > 1) {
    //  concatSql.forEach(condition -> {
    //    Object value = condition.getValues().stream().filter(valueObj -> valueObj != null).findFirst().orElse(null);
    //    if (value != null) {throw new RuntimeException("禁止拼接sql");}
    //  });

    //}
    ////
    //// * 条件参数中，如果有 in ，in 列表不能超过 10 个。
    //TableStat.Condition sizeCondition =
    //  visitor.getConditions().stream().filter(condition -> "IN".equals(condition.getOperator()) && condition.getValues().size() > 10)
    //    .findFirst().orElse(null);
    //if (sizeCondition != null) {
    //  log.info("IN SQL:{}", statement.getSqlStat().getSql());
    //  log.info("getValues:{}", sizeCondition.getValues());
    //  throw new RuntimeException(sizeCondition.getOperator() + "操作参数数量为" + sizeCondition.getValues().size() + ",超过限制数量");
    //
    //}
    return true;
  }

}
